import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:note/common/common.dart';
import 'package:get/get.dart';
import 'package:note/manager/global.dart';
import 'package:note/widgets/dialog.dart';
import 'package:url_launcher/url_launcher.dart';
import '../manager/net/apiManager.dart';
import 'info.dart';

class Tools {
  ///获取设备类型
  static String getDeviceType() {
    final data = MediaQueryData.fromWindow(WidgetsBinding.instance.window);
    return data.size.shortestSide < 600 ? 'phone' : 'tablet';
  }

  ///判断设备是否横屏
  static bool isTabletLandscape(BuildContext context) {
    return MediaQuery.of(context).orientation == Orientation.landscape;
  }

  ///设置系统顶部安全区的颜色
  static void setSystemTopUI() {
    SystemChrome.setSystemUIOverlayStyle(
        const SystemUiOverlayStyle(statusBarColor: Styles.transparent));
  }

  ///检测是否是最新版本，是true，否false
  static Future<bool> checkVersion({bool showTrue = false}) async {
    Map res = await apiManager.getGitInfo();
    String newVersion = res[Info.gitTagName];
    String newVersionContent = res[Info.gitBody];
    if (newVersion != ('v${GlobalUtil.packageInfo?.version}')) {
      //新版本下载框
      Get.dialog(defaultDialog(
          title: Strings.hasNewVersion,
          content: Strings.newVersion(newVersion, newVersionContent),
          sure: Strings.update,
          cancel: Strings.cancel,
          sureFunction: () {
            String url = res['assets'][0]['browser_download_url'].toString();
            Tools.launchURL(url);
          }));
      return false;
    } else {
      if (showTrue) {
        //提示已是最新版
        Toasts.showToast('已是最新版本');
      }
      return true;
    }
  }

  ///打开链接，启动应用
  static void launchURL(String url) async {
    launch(url);
  }
}

///时间转换字符串
class DateTimeToString {
  static String toYYMMDD(DateTime time) {
    return formatDate(time, [yyyy, '-', mm, '-', dd]);
  }

  static String toYYMMDDHSN(DateTime time) {
    return formatDate(
        time, [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss]);
  }

  static String toHHNNSS(DateTime time) {
    return formatDate(time, [HH, ':', nn, ':', ss]);
  }

  static String toYYMD(DateTime time) {
    return formatDate(time, [yy, '-', M, '-', d]);
  }
}

///显示toast
class Toasts {
  static void showToast(String msg, {Color? color, ToastGravity? gravity}) {
    Fluttertoast.showToast(
      msg: msg,
      toastLength: Toast.LENGTH_SHORT,
      // 持续显示时间，Toast.LENGTH_SHORT表示短时间，Toast.LENGTH_LONG表示长时间
      gravity: gravity ?? ToastGravity.CENTER,
      // 显示位置，可以是顶部、中间或底部
      backgroundColor: color ?? Styles.mainThemeColor,
      // 背景颜色 `
      textColor: Colors.white,
      // 文本颜色
      fontSize: 16.0, // 文本大小
    );
  }
}
